<template>
  <div class="step-container" v-loading="loading">
    <template v-if="bussType === '5' || bussType === '6'">
      <div>
        <div class="form-title">水利工程质量检测单位</div>
        <div class="form-title">乙级资质等级认定（初次申请）表</div>
        <div
            ref="wordContainer"
            class="word-container"
            :style="{ height: wordHeight }"
        >
          <div id="word1" class="href-div"></div>
          <Word1 ref="Word1" :formData="formData" :disabled="disabled" />
          <div id="word2" class="href-div"></div>
          <Word2 ref="Word2" :formData="formData" :disabled="disabled" />
          <div id="word3" class="href-div"></div>
          <Word3 ref="Word3" :formData="formData" :disabled="disabled" />
          <!--        <div id="word4" class="href-div"></div>-->
          <!--        <Word4 ref="Word4" :formData="formData" :disabled="disabled" />-->
          <!--        <div id="word5" class="href-div"></div>-->
          <!--        <Word5 ref="Word5" :formData="formData" :disabled="disabled" />-->
          <!--        <div id="word6" class="href-div"></div>-->
          <!--        <Word6 ref="Word6" :formData="formData" :disabled="disabled" />-->
        </div>
      </div>
      <div class="href-link">
        <div class="link-step">
          <div class="step-highlight" :style="{ top: highlightTop }" />
        </div>
        <div class="link-main">
          <div
              v-for="(item, index) in linkList"
              :key="index"
              :class="['link-item', { active: linkActive === index }]"
              @click="link(item, index)"
          >
            {{ item.label }}
          </div>
        </div>
      </div>
    </template>
<!--    MOD-->
    <template v-else-if="bussType === '8'">
      <Word4 ref="Word5"
              :formData="formData"
              :dataChange = "loading"
              :disabled="disabled"></Word4>
    </template>
<!--    EXT-->
    <template v-else-if="bussType === '7'">
      <Word5 ref="Word4"
              :formData="formData"
              :disabled="disabled"></Word5>
    </template>
    <template v-else-if="bussType === '9'">
      <Word6 ref="Word6"
              :formData="formData"
              :disabled="disabled"></Word6>
    </template>
  </div>
</template>
<script>
import Word1 from './components/Word1';
import Word2 from './components/Word2';
import Word3 from './components/Word3';
import Word4 from './components/Word4';
import Word5 from './components/Word5';
import Word6 from './components/Word6';
import businessApi from '@/api/business';
import userApi from '@/api/user';
import { decrypt } from '@/utils/sms4util';

export default {
  props: {
    id: {
      type: String,
    },
    bussType: {
      default: '5',
    },
    disabled: {
      default: false,
    },
    userId: {
      type: String,
    },
    createdId: {
      type: String,
    },
  },
  components: {
    Word1,
    Word2,
    Word3,
    Word4,
    Word5,
    Word6,
  },
  data() {
    return {
      formData: {},
      topHeight: 0,
      linkActive: 0,
      wordHeight: '530px',
      loading: false,
      linkList: [
        { label: '一、检测单位法定代表人声明', href: 'word1' },
        { label: '二、检测单位基本情况', href: 'word2' },
        { label: '三、技术负责人基本情况', href: 'word3' },
      ],
    };
  },
  computed: {
    highlightTop() {
      return this.linkActive * 64 + 'px';
    },
    izStock() {
      return this.$store.state.user.izStock;
    },
    notCq() {
      return (this.formData.unitAddrProCode && this.formData.unitAddrProCode != '500000') ||
          (this.formData.detAddvcdProv && this.formData.detAddvcdProv != '500000');
    }
  },
  mounted() {
    //读取未完成的表单
    this.init();
    if (businessApi.isRegBussType(this.bussType)) {
      this.topHeight = this.$refs.wordContainer.getBoundingClientRect().top;
      this.initWordHeight();
      document
          .querySelector('.word-container')
          .addEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    async init() {
      this.$emit('loading', true);
      // 读取用户信息
      await this.initUserInfo();
      if (this.id) {
        let params = {
          id: this.id,
          type: this.bussType,
        };
        // 读取表单
        await businessApi.getStepsInfo(params).then(async (res) => {
          const photo = await businessApi.getFileList({
            businessId: this.id,
            businessTable: 'TB_APPLY',
            subType: 'jsfzrPhoto'
          });
          this.formData = Object.assign({}, this.formData, {
            ...res,
            id: this.id,
            jsfzrPhoto: photo ? photo[0] : undefined,
            fddbrZjh: res.fddbrZjh ? decrypt(res.fddbrZjh) : undefined,
            unitTel: res.unitTel ? decrypt(res.unitTel) : undefined,
            creditCode: res.creditCode ? decrypt(res.creditCode) : undefined,
            czztdm: res.czztdm ? decrypt(res.czztdm) : undefined,
            conNum: res.conNum ? decrypt(res.conNum) : undefined,
            legRepIdCard: res.legRepIdCard ? decrypt(res.legRepIdCard) : undefined,
          });
          this.formData = Object.assign({}, {
            ...this.formData,
            serviceType: this.formData.serviceType ?
                this.formData.serviceType :
                this.notCq ? '3' : '1',
          })
        }).finally(() => {
          this.$emit('loading', false);
        });

      } else {
        this.formData.id = this.createdId;
        const newFormData = {
          ...this.formData,
          czzt: this.formData.unitName,
          czztdm: this.formData.creditCode,
          estDate: this.formData.unitEstTime,
          entType: this.formData.jjxz,
          detAddvcd: this.formData.unitAddrCountyCode,
          detAddvcdCity: this.formData.unitAddrCityCode,
          detAddvcdProv: this.formData.unitAddrProCode,
          detAddrPart: this.formData.unitAddress,
          conNum: this.formData.unitTel,
          fax: this.formData.unitFax,
          conPc: this.formData.unitPostCode,
          regCapl: this.formData.zczj,
          legRep: this.formData.fddbrXm,
          legRepPost: this.formData.fddbrZw,
          legRepTitleCode: this.formData.fddbrZc,
          tecDire: this.formData.jsfzrXm,
          tecDirePost: this.formData.jsfzrZw,
          tecDireTitleCode: this.formData.jsfzrZc,
        }
        this.formData = Object.assign({}, newFormData);
      }
      if (!this.izStock) {
        this.$store.state.user.izStock = this.formData.izStock;
      }
      this.$emit('loading', false);
    },
    async initUserInfo() {
      let params = {
        id: this.userId || this.$store.state.user.userInfo.id,
        // 企业用户
        type: 2,
      };
      this.$emit('loading', true);
      const res = await userApi.getUserInfo(params).finally(() => {
        this.$emit('loading', false);
      });
      this.formData = {
        ...this.formData,
        ...res,
        appPer: res.realname,
        sqdw: res.unitName,
        creditCode: res.creditCode ? decrypt(res.creditCode) : '',
        unitTel: res.unitTel ? decrypt(res.unitTel) : '',
        unitAddrCode: res.unitAddrCountyCode ? res.unitAddrCountyCode : res.unitAddrCityCode ? res.unitAddrCityCode : res.unitAddrProCode,
        // 固定值
        sqzzlb: '水利工程质量检测单位乙级',
      };
      if (res.paperType === '111' && res.paperCode) {
        this.formData.fddbrZjh = res.paperCode;
      }
    },
    // 目录跳转
    link(item, index) {
      this.linkActive = index;
      document
        .querySelector('#' + item.href)
        .scrollIntoView({ behavior: 'smooth' });
    },
    // 初始化目录高度
    initWordHeight() {
      this.linkList = this.linkList.map((item) => {
        const top =
          document.getElementById(item.href).offsetTop -
          document.getElementById('word1').offsetTop;
        return {
          ...item,
          top,
        };
      });
    },
    // 监听滚动
    handleScroll() {
      let index = 0;
      for (let i = 0; i < this.linkList.length; i++) {
        if (
          document.getElementById(`word${6 - i}`).getBoundingClientRect().top <=
          500
        ) {
          index = 5 - i;
          this.linkActive = index;
          return;
        }
      }
    },
    // 表单校验
    formValidated() {
      let flag = true;
      if (businessApi.isRegBussType(this.bussType)) {
        for (let i = 0; i < this.linkList.length; i++) {
          if (!this.$refs[`Word${i + 1}`].formValidated()) {
            this.link(this.linkList[i], i);
            flag = false;
            return;
          }
        }
      } else {
        return this.$refs[`Word${this.bussType-3}`].formValidated();
      }
      return flag;
    },
    // 保存
    async save(status = 0) {
      if (!this.formValidated()) {
        return Promise.resolve({});
      }
      let params = {
        ...this.formData,
        bussType: this.bussType,
        izStock: this.izStock
      };
      if (this.id || this.createdId) {
        params.applyId = this.id || this.createdId;
      }
      this.$emit('loading', true);
      if ('8' == this.bussType || (this.izStock && '7' == this.bussType)) {
        let fullAddr = businessApi.getAddr(this.formData.detAddvcd, this.formData.detAddvcdCity);
        params = {
          ...params,
          detAddr: fullAddr
        }
      }
      // 根据业务类型调用不同的接口
      const res = await businessApi[`saveUserBusiness${this.bussType}`](
        status,
        params,
      ).finally(() => {
        this.$emit('loading', false);
      });
      this.$message.success('保存成功');
      this.$emit('changeId', res);
      return Promise.resolve({
        infoId: res,
      });
    },
  },
  // 销毁监听事件
  destroyed() {
    removeEventListener('scroll', this.handleScroll);
  }
};
</script>
<style lang="scss" scoped>
.form-title {
  width: 100%;
  margin-top: 20px;
  font-size: 30px;
  font-weight: 600;
  text-align: center;
  padding-left: 160px;
}
.step-container {
  width: 100%;
  display: flex;
  align-items: center;
  .word-container {
    padding: 10px 100px;
    margin-top: 40px;
    margin-left: 160px;
    border: 1px solid #e1e1e1;
    overflow-y: auto;
    .href-div {
      margin-top: 20px;
    }
  }
  .href-link {
    margin-left: 60px;
    display: flex;
    .link-step {
      position: relative;
      margin-right: 20px;
      width: 2px;
      background: #dddddd;
      .step-highlight {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 2px;
        height: 32px;
        background: #3c8cf1;
      }
    }
    .link-main {
      .link-item {
        height: 32px;
        line-height: 32px;
        font-size: 16px;
        color: #666666;
        cursor: pointer;
        &:not(:first-child) {
          margin-top: 32px;
        }
      }
      .active {
        color: #3c8cf1;
      }
    }
  }
}
.word-container::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 6px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 6px;
}
.word-container::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
  background: #dddddd;
}
.word-container::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
  background: #f8f8f8;
}
</style>
